package stack_and_queue.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * @Author Stark
 * @Date 2022/1/24 22:12
 */
public class MyStack<E> {
    private int size;
    private List<E> stack = new ArrayList<>();

    public void push(E val){
        stack.add(val);
        size++;
    }

    public E pop(){
        if(stack.isEmpty()){
            throw new NoSuchElementException("The stack is empty,can't pop!");
        }
        E val = stack.get(size - 1);
        stack.remove(--size);
        return val;
    }

    public E peek(){
        if(stack.isEmpty()){
            throw new NoSuchElementException("The stack is empty,can't peek!");
        }
        return stack.get(size - 1);
    }

    public boolean isEmpty(){
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append("[");
        for (int i = 0; i < size; i++) {
            str.append(stack.get(i));
            if(i < size - 1)
                str.append(",");
        }
        str.append("]");
        return str.toString();
    }
}
